package com.shun.upms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shun.common.R;
import com.shun.common.page.ShunPage;
import com.shun.upms.mapper.SysAdminPostMapper;
import com.shun.upms.mapper.SysAdminUserMapper;
import com.shun.upms.service.ISysAdminPostService;
import com.shun.upms.vo.SysAdminPost;
import com.shun.upms.vo.SysAdminUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统内岗位表 服务实现类
 * </p>
 *
 * @author clever
 * @since 2021-10-10
 */
@Slf4j
@Service
public class SysAdminPostServiceImpl extends ServiceImpl<SysAdminPostMapper, SysAdminPost> implements ISysAdminPostService {

    private final static String ERR_EDIT_POST = "更新岗位失败！";

    private final static String ERR_ADD_POST = "新增岗位失败！";

    private final static String ERR_DEL_POST = "删除岗位失败！";

    private final static String ERR_DEL_USR_POST = "当前岗位存在用户，不能删除！";

    @Autowired
    private SysAdminUserMapper adminUserMapper;

    @Override
    public R addAdminPost(SysAdminPost post) {
        log.debug("post:{}",post);
        String postId = IdUtil.objectId();
        post.setPostId(postId);
        post.setCreateUser(StpUtil.getLoginIdAsString());
        return save(post)?R.suc():R.error(ERR_ADD_POST);
    }

    @Override
    public R delAdminPost(String postId) {
        log.debug("postId:{}",postId);
        List<SysAdminUser> sysAdminUserList = new LambdaQueryChainWrapper<SysAdminUser>(this.adminUserMapper)
                .eq(SysAdminUser::getSauPostId,postId).list();
        if(ObjectUtil.isEmpty(sysAdminUserList)){
            return removeById(postId)?R.suc():R.error(ERR_DEL_POST);
        }
        return R.error(ERR_DEL_USR_POST);
    }

    @Override
    public R editAdminPost(SysAdminPost post) {
        UpdateWrapper<SysAdminPost> updateWrapper = new UpdateWrapper<SysAdminPost>();
        updateWrapper.eq("post_id",post.getPostId());
        boolean flag = update(post,updateWrapper);
        return flag?R.suc():R.error(ERR_EDIT_POST);
    }

    @Override
    public R pageAdminPost(ShunPage<SysAdminPost> page) {
        log.debug("分页信息:{}",page);
        QueryWrapper<SysAdminPost> queryWrapper = new QueryWrapper<SysAdminPost>();
        IPage<SysAdminPost> postPage = page(page.toPage(),queryWrapper);
        return R.suc(postPage);
    }
}
